import fetch from 'dva/fetch';
import qs from 'qs';
import { Modal } from 'antd-mobile';
import React from 'react';
import { getFullUrl, gotoLoginAndBack, isWechat, publicWXAppID, SERVER_DOMAIN, gotoLogin,getPath } from './common';
import { getSign } from './doSign';
import { getIsLz, getIsFalse } from './judgmentEquipment'

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}
// 保存的上一次的Url
var url = "";
export var isJudg = false;


export async function request(requestUrl, options, isGoToLogin) {
  //let num=1;
  //const url = getFullUrl(requestUrl);
  const response = await fetch(requestUrl, options);
  checkStatus(response);
  const data = await response.json();

  //console.log(isGoToLogin);
  if (isGoToLogin === undefined) {
    isGoToLogin = true;
  }

  if (isGoToLogin == true ) {
    if (data.code == '401' || data.msg.includes('请先登录') > 0) {

      // if (isWechat()) {
      //   // // 公众平台号appid 登录授权
      //   // // 域名
      //   //
      //   // localStorage.setItem('history', location.href);
      //   // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${publicWXAppID}&redirect_uri=${encodeURIComponent(SERVER_DOMAIN)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirec`;
      //  // return json;
      // } else {
        if (!getIsLz()) {
            if(requestUrl.indexOf("/rest/api/v6.0/cart/settlement")!=-1){
                window.location.replace(getPath()+ "/login"+"?callBack="+encodeURIComponent(window.location.href))
                // window.location.href = "/login";
                localStorage.removeItem('token');
                sessionStorage.removeItem('token');
            }else if(requestUrl.indexOf("/rest/api/v6.0/trends/conners")==-1&&requestUrl.indexOf("/rest/api/v6.0/trends/first/enter")==-1) {
                Modal.alert("", <div style={{ lineHeight: '0.9rem', fontSize: "0.3rem",padding:".5rem",color:"#333" }}>请先登录!</div>, [ {
                    text: '取消',
                    onPress: () => {
                        localStorage.removeItem('token');
                        sessionStorage.removeItem('token');
                        getIsFalse();
                        // window.location.href="/";
                        // window.history.back();
                    },
                },{
                    text: '去登录',
                    onPress: () => {
                        gotoLoginAndBack();
                        // window.location.href = "/login";
                        localStorage.removeItem('token');
                        sessionStorage.removeItem('token');
                        getIsFalse();
                    },
                }]);
            }

        }
      }
    // } else {
    //
    // }
  }
  isJudg = false;
  return (data);
}

export function get(requestUrl, params, isGoToLogin) {
    const baseParams = {
        timestamp: new Date().getTime() + "" +  Math.floor(Math.random()*100000000)
    };

    params = {
        ...baseParams,
        ...params,
    };
    let url = getFullUrl(requestUrl);
    if (params) {
        url = `${url}?${qs.stringify(params)}&sign=${getSign(params)}`;
    }
    const token = localStorage.getItem('token');
    const headers = { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' };
    if (token) {
        headers.token = token;
    }
    return request(url, {
            credentials: 'include',
            headers,
            method: 'GET',
        },
        isGoToLogin,
    );
}

export function upload(requestUrl, data) {
    const baseParams = {
        timestamp: new Date().getTime()
    }
   // const token = sessionStorage.getItem('token');
    let formData = new FormData();
    console.log(data)
    if(data.video==undefined){
        if (Array.isArray(data.upfile)) {
            data.upfile.forEach(function (element) {
                formData.append('upfile', element);
            });
        } else {
            formData.append('upfile', data.upfile)
        }
    }else{
        if (Array.isArray(data.video)) {
            data.video.forEach(function (element) {
                formData.append('video', element);
            });
        } else {
            formData.append('video', data.video)
        }
    }

    let url = getFullUrl(requestUrl);
  //  console.log(url)
    let headers = {}
    // if (token) {
    //     headers['token'] = token;
    // }
    console.log(formData,formData.get("upfile"))
    return fetch(url, {
        method: 'POST',
        headers,
        mode: 'cors',
        credentials: 'include',
        body: formData
    }).then(res => res.json());
}

export function post(requestUrl, params, isGoToLogin) {
    const baseParams = {
        timestamp: new Date().getTime() + "" +  Math.floor(Math.random()*100000000)
    }

    let url = getFullUrl(requestUrl);
    //const token = localStorage.getItem('token');
    let param = {
        ...baseParams,
        ...params
    }
    params = {
        ...param,
        sign:decodeURIComponent(getSign(param))
    }
    let headers = {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    }
    // if (token) {
    //     headers['token'] = token;
    // }

    return request(url, {
            credentials: 'include',
            headers,
            method: "POST",
            body: qs.stringify(params),
        },
        isGoToLogin,
    );
}


export function del(requestUrl, params, isGoToLogin) {
    const baseParams = {
        timestamp: new Date().getTime() + "" +  Math.floor(Math.random()*100000000)
    };

    params = {
        ...baseParams,
        ...params,
    };
    let url = getFullUrl(requestUrl);
    if (params) {
        url = `${url}?${qs.stringify(params)}&sign=${getSign(params)}`;
    }
   // const token = localStorage.getItem('token');
    const headers = { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' };
    // if (token) {
    //     headers.token = token;
    // }
    return request(url, {
            credentials: 'include',
            headers,
            method: 'DELETE',
        },
        isGoToLogin,
    );
}

export  function patch(requestUrl,params) {

    const baseParams = {
        timestamp: new Date().getTime() + "" +  Math.floor(Math.random()*100000000)
    }

    let url = getFullUrl(requestUrl);
    //const token = localStorage.getItem('token');
    let param = {
        ...baseParams,
        ...params
    }
    params = {
        ...param,
        sign:decodeURIComponent(getSign(param))
    }

    return request(url, {
        method: 'PATCH',
        headers : {
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
            // 'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: qs.stringify(params)
    });
}

export  function put(requestUrl,values) {
    let url = getFullUrl(requestUrl);
    return request(url, {
        method: 'PUT',
        headers : {
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
            // 'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: qs.stringify(values)
    });
}

export function getState(is) {
    isJudg = is;
}
